package com.mvc.controller;
import com.mvc.queue.JamesDefferdQueue;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.UUID;
import java.util.concurrent.Callable;

@Controller
public class AsyncOrderController {
    /**
     * MVC异步请求
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("/order")
    public Callable<String> order() {
        System.out.println("主线程开始..." + Thread.currentThread().getName() + "==>" + System.currentTimeMillis());
        Callable<String> callable = new Callable<String>() {//完成异步
            @Override
            public String call() throws Exception {
                System.out.println("副线程开始..." + Thread.currentThread().getName() + "==>" + System.currentTimeMillis());
                Thread.sleep(5000);
                System.out.println("副线程开始..." + Thread.currentThread().getName() + "==>" + System.currentTimeMillis());

                return "order buy successful";//向页面返回的内容
            }

        };
        System.out.println("主线程结束..." + Thread.currentThread().getName() + "==>" + System.currentTimeMillis());
        return callable;
    }



    //其实相当于我们说的tomcat的线程1，来处理用户请求，并将请求的操作放到Queue队列里
    @ResponseBody
    @RequestMapping("/createOrder")
    public DeferredResult<Object> createOrder() {

        DeferredResult<Object> deferredResult = new DeferredResult<>((long) 5000, "create fail...");//等待时间-超时返回的错误提示
        JamesDefferdQueue.save(deferredResult);//将请求保存到Queue队列

        return deferredResult;
    }


    //其实相当于我们说的tomcat的线程N,来处理用户请求，并将请求的操作放到Queue队列里
    @ResponseBody
    @RequestMapping("/create")
    public String create(){
        //创建订单（按真实操作应该是从订单服务取，这里直接返回）
        String orderId = UUID.randomUUID().toString();//模拟从订单服务获取的订单信息（免调接口）
        DeferredResult<Object> deferredResult = JamesDefferdQueue.get();
        deferredResult.setResult(orderId);//线程N对DeferredResu1t将订单服务返回的信息进行设值
        return "create success  orderId == " + orderId;
    }
}
